package com.cheyun.netsalev3.view

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.annotation.NonNull
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationManagerCompat
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.cheyun.netsalev3.HomeMyFragment
import com.cheyun.netsalev3.MyApplication
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.adapter.HomePageAdapter
import com.cheyun.netsalev3.bean.dm.DmLogin
import com.cheyun.netsalev3.bean.drive.ReserveInfo
import com.cheyun.netsalev3.databinding.ActivityMainBinding
import com.cheyun.netsalev3.tencenttim.utils.DemoLog
import com.cheyun.netsalev3.utils.*
import com.cheyun.netsalev3.utils.api.*
import com.cheyun.netsalev3.utils.api.dm.DmApiCallback
import com.cheyun.netsalev3.utils.api.dm.DmApiException
import com.cheyun.netsalev3.view.allocated.AllocatedActivity
import com.cheyun.netsalev3.view.home.HomeTaskFragment1
import com.cheyun.netsalev3.view.home.HomeTaskFragment2
import com.dou361.dialogui.DialogUIUtils
import com.dou361.dialogui.listener.DialogUIListener
import com.igexin.sdk.PushManager
import com.jeremyliao.liveeventbus.LiveEventBus
import com.tbruyelle.rxpermissions3.RxPermissions
import com.tencent.qcloud.tim.uikit.TUIKit
import com.yxing.ScanCodeConfig
import com.yxing.def.ScanMode
import com.yxing.def.ScanStyle
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import java.io.Serializable
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.MutableMap
import kotlin.collections.set
import kotlin.collections.toTypedArray

class MainActivity : BaseActivity<ActivityMainBinding>(){
    override fun initContentView(): Int {
        return R.layout.activity_main
    }

    var titles = ArrayList<String>()
    var nkeys = ArrayList<String>()
    var context: Context? = null

    var enableStartChat = true;

    val handler = Handler()

    init {
        var loginData = MySharedPreferences.getLoginData()

        var isadmin = loginData?.member?.isadmin ?: 0
        isadmin = 1
        if (isadmin == 1) {
            titles.add("跟进")
            nkeys.add("archive.purge")
            titles.add("订车")
            nkeys.add("archive.order")
            titles.add("提车")
            nkeys.add("archive.thenend")
        } else {
            loginData?.member?.apps?.chance?.apply {
                for (i in this) {
                    when (i) {
                        "1201" -> {
                            titles.add("跟进")
                            nkeys.add("archive.purge")
                        }
                        "1202" -> {
                            titles.add("订车")
                            nkeys.add("archive.order")
                        }
                        "1203" -> {
                            titles.add("提车")
                            nkeys.add("archive.thenend")
                        }
                    }
                }
            }
        }
    }

    private var listFragmet = ArrayList<Fragment>()

    override fun initView() {

        //  0 个人 1 管理层 2 展厅
        var workbench = MySharedPreferences.getWorkbench()
        when (workbench) {
            0 -> listFragmet.add(HomeTaskFragment2())
            1 -> listFragmet.add(HomeTaskFragment1())
            2 -> listFragmet.add(HomeTaskFragment3.newInstance("home"))
        }

        if (nkeys.size > 0) {
            listFragmet.add(HomeCustomerFragment())
        } else {
            binding.homeCustomer.visibility = View.GONE
            binding.addLayout.visibility = View.GONE
        }
//        listFragmet.add(HomeCustomerFragment())

        listFragmet.add(HomeAppFragment())
        listFragmet.add(HomeMyFragment())
        val pagerAdapter = HomePageAdapter(supportFragmentManager, listFragmet)
        binding.viewPager.adapter = pagerAdapter
        binding.viewPager.offscreenPageLimit = 4


        //test
//        val pageAdapter = FragmentLazyPagerAdapter(supportFragmentManager,listFragmet,ArrayList<String>())
//        binding.viewPager.adapter = pageAdapter
//        binding.viewPager.offscreenPageLimit = 4
        //test end

        binding.homeTask.isChecked = true
        //设置底部按钮事件
        binding.homeLayout.setOnCheckedChangeListener { group, checkedId ->
            if (nkeys.size > 0) {
                when (checkedId) {
                    R.id.homeTask -> {
                        viewPager.setCurrentItem(0, true)
                    }
                    R.id.homeCustomer -> {
                        viewPager.setCurrentItem(1, true)
                    }
                    R.id.homeAnalys -> {
                        viewPager.setCurrentItem(2, true)
                    }
                    R.id.homeMy -> {
                        viewPager.setCurrentItem(3, true)
                    }
                }
            } else {
                when (checkedId) {
                    R.id.homeTask -> {
                        viewPager.setCurrentItem(0, true)
                    }
                    R.id.homeAnalys -> {
                        viewPager.setCurrentItem(1, true)
                    }
                    R.id.homeMy -> {
                        viewPager.setCurrentItem(2, true)
                    }
                }
            }
        }
        //设置滑动监听器
        binding.viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                changeBottonView(position)
            }
        })

        binding.addBut.setOnClickListener {
            //非VIP版本显示功能   悬浮里不用添加线索
            var hasAuthorization = MySharedPreferences.hasAuthorization()
            if(hasAuthorization){
                addClue()
            }else{
                MyToast("此功能只对VIP用户开启")
            }
        }
        context = this

        checkNotificationsEnabled()

//        LiveEventBus.get()
//                .with("scan", String::class.java)
//                .observe(this, Observer {
//                    Log.d("mainactivity","call scan")
//                    startScan(ScanStyle.WECHAT)
//                })
//        LiveEventBus.get()
//                .with("scanReal", String::class.java)
//                .observe(this, Observer {
//                    Log.d("mainactivity","call scan")
//                    realOpen()
//                })


        if(GlobalConfig._schemeTo){
            var intent = Intent(this, AllocatedActivity::class.java)
            startActivity(intent)
            GlobalConfig._schemeTo = false
        }
    }

    private val REQ_PERMISSION_CODE = 0x100
    //权限检查
    fun checkPermission(activity: Activity): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val permissions = java.util.ArrayList<String>()
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(TUIKit.getAppContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(TUIKit.getAppContext(), Manifest.permission.CAMERA)) {
                permissions.add(Manifest.permission.CAMERA)
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(TUIKit.getAppContext(), Manifest.permission.RECORD_AUDIO)) {
                permissions.add(Manifest.permission.RECORD_AUDIO)
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(TUIKit.getAppContext(), Manifest.permission.READ_PHONE_STATE)) {
                permissions.add(Manifest.permission.READ_PHONE_STATE)
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(TUIKit.getAppContext(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
            if (permissions.size != 0) {
                val permissionsArray = permissions.toTypedArray()
                ActivityCompat.requestPermissions(activity,
                        permissionsArray,
                        REQ_PERMISSION_CODE)
                return false
            }
        }
        return true
    }

    private fun addClue(){
        if(MyApplication.getInstance().atAddClueActivity) return
        startActivity(Intent(this, AddClueActivity::class.java))
    }

//    private fun startChat(){
//        if(MyApplication.getInstance().atChatActivity ) return
//        if(enableStartChat) {
//            enableStartChat = false
//            var hasPermission = checkPermission(this)
//            if (hasPermission) {
//                dmLogin();
//            }
//        }
//    }
    private fun dmLogin(){
        var channel = MySharedPreferences.getLoginData()?.channel?.id;
        var password: String = MySharedPreferences.getPassword()
        var mobile: String = MySharedPreferences.getMobile()
        var dialog = DialogUIUtils.showLoadingVertical(this,"加载中...").show();
        DmApiClient.getInstance().login(mobile, CommonFunc.textToMD5L32(password), channel!!)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DmApiCallback<DmBaseResp<DmLogin, Any>>() {
                    override fun onSuccess(t: DmBaseResp<DmLogin, Any>) {
                        t.list.apply {
                            MySharedPreferences.putDMCauthkey(this?.auth.toString())
                            MySharedPreferences.putDMMgr(this?.clue_mgr!!)
                            MySharedPreferences.putDmLoginData(this);
                            startActivity(Intent(context, TimChatActivity::class.java))
                        }
                        dialog?.dismiss();
                        enableStartChat = true
                    }
                    override fun onError(ex: DmApiException) {
                        dialog?.dismiss();
                        enableStartChat = true
                        Log.e("dm login",ex.getMessage())
                        Looper.prepare()
                        MyToast(ex.getMessage()!!);
                        Looper.loop()
                    }
                })
    }

    private fun checkNotificationsEnabled(){
        if (!NotificationManagerCompat.from(MyApplication.getInstance().baseContext).areNotificationsEnabled()) {
            var dialog = DialogUIUtils.showAlert(this, "通知打开提醒", "为保证及时收到推送消息，请您手动将通知开启", object : DialogUIListener() {
                override fun onPositive() {
                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT <  Build.VERSION_CODES.O) {
                        var intent = Intent()
                        intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS")
                        intent.putExtra("app_package", MyApplication.getInstance().packageName)
                        intent.putExtra("app_uid", context?.getApplicationInfo()?.uid)
                        startActivity(intent);
                    } else if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
                        var intent = Intent()
                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                        intent.setData(Uri.parse("package:" + MyApplication.getInstance().packageName));
                        startActivity(intent);
                    } else {
                        var localIntent = Intent()
                        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                        localIntent.setData(Uri.fromParts("package", MyApplication.getInstance().packageName, null));
                        startActivity(localIntent);
                    }
                }

                override fun onNegative() {

                }
            }).show()

            val dialogWindow = dialog?.getWindow()
            val p = dialogWindow?.getAttributes() // 获取对话框当前的参数值
            // 设置宽度
            p?.width = (windowManager.defaultDisplay.width * 0.95).toInt() // 宽度设置为屏幕的0.95
            p?.gravity = Gravity.CENTER//设置位置
            //p.alpha = 0.8f;//设置透明度
            dialogWindow?.setAttributes(p)
        }else{
//            var win = getWindow()
//            win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)
        }
    }

    /**
     * 系统请求权限回调
     */
    override fun onRequestPermissionsResult(requestCode: Int, @NonNull permissions: Array<String>, @NonNull grantResults: IntArray) {
        when (requestCode) {
            REQ_PERMISSION_CODE ->{
                super.onRequestPermissionsResult(requestCode, permissions, grantResults)
                dmLogin()
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    ToastUtil.toastLongMessage("未全部授权，部分功能可能无法使用！")
                }
            }
        }
    }
    /**
     * 设置别名
     *
     * @param uid
     */
    private fun setAlias(uid: Int) {
        DemoLog.d("call bindAlias",uid.toString())
        if (uid == 0) {
            return
        }
//        JPushInterface.setAlias(this, 1, uid.toString())
        PushManager.getInstance().bindAlias(this, uid.toString())
    }
    /**
     * 设置别名（智投）
     *
     * @param uid
     */
    private fun setDMAlias(uid: Int) {
        if (uid == 0) {
            return
        }
//        JPushInterface.setAlias(this, 1,"DM_USER_"+uid)
        PushManager.getInstance().bindAlias(this,"DM_USER_"+ uid)
    }

    override fun initData() {
        var uid = MySharedPreferences.getLoginData()?.member?.uid ?: 0
        DemoLog.d("initData",uid.toString())
        setAlias(uid)
//        if(!ThirdPushTokenMgr.getInstance().thirdPushToken.isNullOrEmpty()){
//            NoticeApiClient.getInstance().setFactoryAlias(DmApiStores.NOTICE_APP_ID,DmApiStores.NOTICE_APP_KEY,
//                    MyApplication.getInstance().getThirdCode(),uid.toString(),ThirdPushTokenMgr.getInstance().thirdPushToken)
//                    .subscribeOn(Schedulers.io())
//                    .subscribeOn(AndroidSchedulers.mainThread())
//                    .subscribe(object : DmApiCallback<DmBaseResp<Any, Any>>() {
//                        override fun onSuccess(t: DmBaseResp<Any, Any>) {
//
//                        }
//
//                        override fun onError(ex: DmApiException) {
//
//                        }
//                    })
//        }

        checkPwd()
    }

//    override fun onResume() {
//        super.onResume()
////        checkNotificationsEnabled()
//    }

    private fun changeBottonView(position: Int) {
        if (nkeys.size > 0) {
            when (position) {
                0 -> homeLayout.check(R.id.homeTask)
                1 -> homeLayout.check(R.id.homeCustomer)
                2 -> homeLayout.check(R.id.homeAnalys)
                3 -> homeLayout.check(R.id.homeMy)
            }
        } else {
            when (position) {
                0 -> homeLayout.check(R.id.homeTask)
                1 -> homeLayout.check(R.id.homeAnalys)
                2 -> homeLayout.check(R.id.homeMy)
            }
        }
    }

    fun checkPwd(){
        if(MySharedPreferences.getLoginData()?.member?.pwdday!! <=15){
            var dialog = AlertDialog.Builder(this)
                    .setTitle("密码修改提示")
                    .setMessage("距离锁定密码已小于15天，请及时修改")
                    .setPositiveButton("去修改"){ dialog, which ->  forget() }
                    .setNegativeButton("取消") { dialog, which ->  }
                    .show()
//            var window = dialog.window
//            if(dialog != null && window != null){
//                var attr = window.getAttributes();
//                if (attr != null) {
//                    attr.height = ViewGroup.LayoutParams.WRAP_CONTENT;
//                    attr.width = ViewGroup.LayoutParams.WRAP_CONTENT;
//                    attr.gravity = Gravity.CENTER;
//                }
//            }
            FunctionUtils.setAlertDialogPos(dialog)
        }
    }

    fun forget(){
        var intent = Intent(this, ForgetActivity::class.java)
        intent.putExtra("to","login")
        this.startActivity(intent)
    }

    //var hasOpenScan = false
    //开始扫描
    private fun startScan(style: Int) {
        Log.d("mainactivity","call scan2" + ","+ MyScanActivity.hasOpenScan)
        try {
            RxPermissions(this).requestEach(
                    Manifest.permission.CAMERA,
                    Manifest.permission.SYSTEM_ALERT_WINDOW
            ).subscribe {
                if (it.granted) {
                   realOpen()
                } else if (it.shouldShowRequestPermissionRationale) {
                    DemoLog.e("camera", "shouldShowRequestPermissionRationale");
                } else {
                    DemoLog.e("camera", "error");
                    MyToast("请确认是否已禁止应用使用手机相机功能")
                }
            }
        }catch (e:Exception){
            e.printStackTrace()
//            PgyerSDKManager.reportException(e)
        }

    }

    fun realOpen(){
        MyScanActivity.mainContext = this
        //MyScanActivity.qrcode = "IFy87POqTSgY60BSvYs4EoGKuDiglEU2WbvS6TRR1axLoDt9MQdZ37jIsk9IwjU4T4wsJKYs6YED367HbGDq98WoQab6DeGPv3co5bm6JCYtK/orPQuAbgLTkel52p0EW4Bfi+PF0AzYNqfRZme/3QhVASOVbPzJ8rJamsbqIcqn6UfUmbsqWrCATu+FNM2JbRVr4ekhBBI="
        if(!MyScanActivity.hasOpenScan) {
            MyScanActivity.hasOpenScan = true
            Log.d("mainactivity", "enable scan")

            ScanCodeConfig.create(this@MainActivity)
                    //设置扫码页样式 ScanStyle.NONE：无  ScanStyle.QQ ：仿QQ样式   ScanStyle.WECHAT ：仿微信样式  ScanStyle.CUSTOMIZE ： 自定义样式
                    .setStyle(ScanStyle.CUSTOMIZE)
                    //扫码成功是否播放音效  true ： 播放   false ： 不播放
                    .setPlayAudio(true)
                    //设置音效音频
                    .setAudioId(R.raw.beep)
                    ////////////////////////////////////////////
                    //以下配置 在style为 ScanStyle.CUSTOMIZE 时生效
                    //设置扫码框位置  left ： 边框左边位置   top ： 边框上边位置   right ： 边框右边位置   bottom ： 边框下边位置   单位/dp
                    //                                    .setScanRect(new ScanRect(50, 200, 300, 450), false)
                    //设置扫码框位置 scanSize : 扫码框大小   offsetX ： x轴偏移量    offsetY ：y轴偏移量   单位 /px
                    .setScanSize(800, 0, -200)
                    //是否显示边框上四个角标 true ： 显示  false ： 不显示
                    .setShowFrame(true)
                    //设置边框上四个角标颜色
                    .setFrameColor(R.color.white)
                    //设置边框上四个角标圆角  单位 /dp
                    .setFrameRaduis(2)
                    //设置边框上四个角宽度 单位 /dp
                    .setFrameWith(4)
                    //设置边框上四个角长度 单位 /dp
                    .setFrameLenth(15)
                    //设置是否显示边框外部阴影 true ： 显示  false ： 不显示
                    .setShowShadow(true)
                    //设置边框外部阴影颜色
                    .setShaowColor(R.color.black_tran30)
                    //设置扫码条运动方式   ScanMode.REVERSE : 往复运动   ScanMode.RESTART ：重复运动    默认ScanMode.RESTART
                    .setScanMode(ScanMode.REVERSE)
                    //设置扫码条扫一次时间  单位/ms  默认3000
                    .setScanDuration(3000)
                    //设置扫码条图片
                    .setScanBitmapId(R.drawable.scan_wechatline)
                    //////////////////////////////////////////////
                    .buidler()
                    //跳转扫码页   扫码页可自定义样式
                    .start(MyScanActivity::class.java)

            if(MyScanActivity.qrcode.isNotEmpty()){
                getScanData(MyScanActivity.qrcode)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == ScanCodeConfig.QUESTCODE && data != null) {
            val extras = data.extras
            if (extras != null) {
                val code = extras.getString(ScanCodeConfig.CODE_KEY)
                DemoLog.i("",String.format("%s%s", "结果： ", code))
                getScanData(code)
            }
        }
    }

    fun showCustomAlert(reserveInfo:ReserveInfo) {
        val myDialogBox = android.app.AlertDialog.Builder(this)
        myDialogBox.setTitle("扫码提示")
        myDialogBox.setMessage("是否核销？")
        myDialogBox.setCancelable(false)
        myDialogBox.setPositiveButton("确认") { dialog, whichButton ->
            doHexiao(reserveInfo)
            dialog.dismiss()
        }
        myDialogBox.setNegativeButton("取消") { dialog, which -> dialog.dismiss() }
        val alertDialog = myDialogBox.create()
        alertDialog.window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
        alertDialog.show()
    }


    fun getScanData(code:String){
        doScanData(code);
    }


    fun doScanData(code:String){
        ApiClient.getInstance().getReserveInfo(code,"","","")
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(object : ApiCallback<BaseResp<ReserveInfo>>() {
                    override fun onSuccess(t: BaseResp<ReserveInfo>) {
                        if (t.state == "y") {
//                            kFunction1(t.data!!)
                            if(t.data?.qrtype == "award"){
                                showCustomAlert(t.data!!)
//                                LiveEventBus.get().with("showQuanyiConfirm").postValue("")
                            }else{
                                var intent = Intent(context, EditCustomStoreActivity::class.java)
                                intent.putExtra("scanData",t.data!! as Serializable)
                                startActivity(intent)
                            }

                        }
                    }
                    override fun onError(ex: ApiException) {

                    }


                })
    }

    fun doHexiao(reserveInfo:ReserveInfo){
        val map: MutableMap<String, String> = HashMap()
        map["ikey"] = reserveInfo.ikey
        map["awardID"] = reserveInfo.awardID
        map["appID"] = reserveInfo.appID
        map["cemID"] = reserveInfo.cemID
        map["qrtime"] = reserveInfo.qrtime

        ApiClient.getInstance().orderquanyiCheck(map)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(object : ApiCallback<BaseResp<Any>>() {
                    override fun onSuccess(t: BaseResp<Any>) {
                        Toast.makeText(context, "核销成功", Toast.LENGTH_LONG).show()
                    }

                    override fun onError(ex: ApiException) {

                    }

                })
    }
}
